package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/pquerna/otp"
	"github.com/pquerna/otp/totp"
	"net/http"
	"time"
)

func TotpPage(c *gin.Context) {
	c.HTML(http.StatusOK, "totp.html", gin.H{})
}

func TotpGenerate(c *gin.Context) {
	url := c.PostForm("url")
	key, err := otp.NewKeyFromURL(url)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  err.Error(),
		})
		return
	}
	now := time.Now()
	code, _ := totp.GenerateCode(key.Secret(), now)
	var expiredTime int
	for i := 0; i < 61; i++ {
		newCode, _ := totp.GenerateCode(key.Secret(), now.Add(time.Duration(i)*time.Second))
		if newCode != code {
			expiredTime = i
			break
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 1,
		"data": gin.H{
			"code":        code,
			"expiredTime": expiredTime,
		},
	})
}
